package com.bruan.reflect;
import org.junit.Test;
import java.lang.reflect.Constructor;

public class Test2Constructor {
    @Test
    public void testGetConstructors(){
        Class c = Cat.class;
        //获取全部构造(公有)
        Constructor[] constructors = c.getConstructors();
        //遍历数组中的构造器对象
        for (Constructor constructor : constructors) {
            System.out.println(constructor.getName()+"--->"+constructor.getParameterCount());
        }
        //获取全部构造器
        Constructor[] constructors1 = c.getDeclaredConstructors();
        for (Constructor constructor : constructors1) {
            System.out.println(constructor.getName()+"--->"+constructor.getParameterCount());
        }
    }

    @Test
    public void testGetConstructor() throws Exception {
        Class c = Cat.class;
        //获取无参构造器
        Constructor constructor = c.getConstructor();
        System.out.println(constructor.getName()+"--->"+constructor.getParameterCount());

        constructor.setAccessible(true);//禁止检查访问权限
        Cat cat = (Cat)constructor.newInstance();//创建对象
        System.out.println(cat);

        //获取具体的有参数构造器 记得加上xxx.class
        Constructor constructor2 = c.getDeclaredConstructor(String.class, int.class);
        System.out.println(constructor2.getName()+"--->"+constructor2.getParameterCount());

        Cat cat1 = (Cat)constructor2.newInstance();//创建对象
        System.out.println(cat1);
    }
}
